#include <iostream>
#include <string>
#include "viml/compiler.h"
#include "viml/vm.h"
#include "viml/parser.h"
#include "viml/ast.h"

using namespace viml;

void print_header(const std::string& title) {
    std::cout << "\n" << std::string(60, '=') << std::endl;
    std::cout << " " << title << std::endl;
    std::cout << std::string(60, '=') << std::endl;
}

void analyze_function_source(const std::string& title, const std::string& source, 
                           Compiler& compiler, VM& vm) {
    std::cout << "\n--- " << title << " ---" << std::endl;
    std::cout << "函数代码：" << std::endl;
    std::cout << source << std::endl;
    
    try {
        // 解析源代码以获取AST
        Parser parser(source);
        auto program = parser.parse();
        
        // 查找函数定义
        for (auto& stmt : program->statements) {
            if (auto func_stmt = dynamic_cast<FunctionStatement*>(stmt.get())) {
                std::cout << "\n分析函数: " << func_stmt->name << std::endl;
                
                // 使用虚拟机的自动分析功能
                auto analysis_result = vm.analyze_and_add_function(*func_stmt);
                
                std::cout << "分析结果：" << std::endl;
                std::cout << "  是否为纯函数: " << (analysis_result.is_pure ? "是" : "否") << std::endl;
                std::cout << "  是否有副作用: " << (analysis_result.has_side_effects ? "是" : "否") << std::endl;
                std::cout << "  是否依赖外部状态: " << (analysis_result.has_external_dependency ? "是" : "否") << std::endl;
                
                if (!analysis_result.global_variables_accessed.empty()) {
                    std::cout << "  访问的全局变量: ";
                    for (size_t i = 0; i < analysis_result.global_variables_accessed.size(); ++i) {
                        if (i > 0) std::cout << ", ";
                        std::cout << analysis_result.global_variables_accessed[i];
                    }
                    std::cout << std::endl;
                }
                
                if (!analysis_result.function_calls.empty()) {
                    std::cout << "  调用的函数: ";
                    for (size_t i = 0; i < analysis_result.function_calls.size(); ++i) {
                        if (i > 0) std::cout << ", ";
                        std::cout << analysis_result.function_calls[i];
                    }
                    std::cout << std::endl;
                }
                
                if (!analysis_result.reason.empty()) {
                    std::cout << "  说明: " << analysis_result.reason << std::endl;
                }
                
                if (analysis_result.is_pure) {
                    std::cout << "  ✓ 函数已自动添加到记忆化白名单" << std::endl;
                } else {
                    std::cout << "  ✗ 函数未添加到记忆化白名单" << std::endl;
                }
            }
        }
    } catch (const std::exception& e) {
        std::cout << "分析出错: " << e.what() << std::endl;
    }
}

int main() {
    try {
        Compiler compiler;
        VM vm;
        
        // 启用记忆化
        vm.set_memoization_enabled(true);
        
        print_header("VimL自动函数纯度分析演示");
        std::cout << "本演示展示VimL虚拟机如何自动判断函数是否可记忆化..." << std::endl;
        
        // 示例1：纯函数（递归数学函数）
        std::string pure_function = R"(
function factorial(n)
    if n <= 1
        return 1
    endif
    return n * factorial(n - 1)
endfunction
        )";
        
        analyze_function_source("示例1：纯函数（阶乘）", pure_function, compiler, vm);
        
        // 示例2：有副作用的函数（包含echo）
        std::string impure_function_echo = R"(
function debug_factorial(n)
    echo "计算阶乘:", n
    if n <= 1
        return 1
    endif
    return n * debug_factorial(n - 1)
endfunction
        )";
        
        analyze_function_source("示例2：有副作用的函数（包含echo）", impure_function_echo, compiler, vm);
        
        // 示例3：依赖外部状态的函数
        std::string external_dependency = R"(
function use_global(x)
    return x + global_variable
endfunction
        )";
        
        analyze_function_source("示例3：依赖外部状态的函数", external_dependency, compiler, vm);
        
        // 示例4：纯函数（字符串处理）
        std::string pure_string_function = R"(
function string_length_sum(a, b)
    return len(a) + len(b)
endfunction
        )";
        
        analyze_function_source("示例4：纯函数（字符串处理）", pure_string_function, compiler, vm);
        
        // 示例5：调用未知函数
        std::string unknown_function_call = R"(
function mystery_calc(x)
    return unknown_function(x) + 1
endfunction
        )";
        
        analyze_function_source("示例5：调用未知函数", unknown_function_call, compiler, vm);
        
        print_header("总结");
        std::cout << "自动函数纯度分析功能特点：" << std::endl;
        std::cout << "1. 自动识别纯函数并添加到记忆化白名单" << std::endl;
        std::cout << "2. 检测副作用操作（如echo、文件操作等）" << std::endl;
        std::cout << "3. 检测外部依赖（如全局变量访问）" << std::endl;
        std::cout << "4. 基于已知函数库的智能判断" << std::endl;
        std::cout << "5. 保守的分析策略，确保缓存安全性" << std::endl;
        
        auto stats = vm.get_memoization_statistics();
        std::cout << "\n当前记忆化状态：" << std::endl;
        std::cout << "  启用状态: " << (vm.is_memoization_enabled() ? "启用" : "禁用") << std::endl;
        std::cout << "  缓存大小: " << stats.size << std::endl;
        
    } catch (const std::exception& e) {
        std::cerr << "演示程序出错: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}